package com.heima.search.service.Impl;

import com.alibaba.fastjson.JSON;
import com.heima.feigns.behavior.BehaviorFeign;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import com.mongodb.operation.OrderBy;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {

    @Autowired
    RestHighLevelClient client;

    @Autowired
    ApUserSearchService apUserSearchService;

    @Value("${file.oss.web-site}")
    private String webSite;


    /**
     * ES文章分页搜索
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) {
        //参数校验
        if (dto == null || StringUtils.isBlank(dto.getSearchWords())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }


        //查询搜索记录  异步调用
        apUserSearchService.insert(dto);


        //构建查询，执行查询
        SearchRequest request = new SearchRequest("app_info_article");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //构建查询条件和过滤
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        //关键词查询
        MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("title", dto.getSearchWords());
        boolQueryBuilder.must(queryBuilder);

        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime().getTime());
        boolQueryBuilder.filter(rangeQueryBuilder);

        //分页
        sourceBuilder.from(0);
        sourceBuilder.size(dto.getPageSize());

        //倒序
        sourceBuilder.sort("publishTime", SortOrder.DESC);

        //高亮三要素
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color:red'>");
        highlightBuilder.postTags("</font>");
        sourceBuilder.highlighter(highlightBuilder);

        sourceBuilder.query(boolQueryBuilder);

        request.source(sourceBuilder);

        List<Map> resultList = new ArrayList<>();
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            //解析结果并封装
            SearchHit[] hits = response.getHits().getHits();


            long total = response.getHits().getTotalHits().value;

            for (SearchHit hit : hits) {
                String jsonString = hit.getSourceAsString();
                Map map = JSON.parseObject(jsonString, Map.class);

                map.put("id", map.get("id").toString());
                //获取高亮结果集
                Text[] titles = hit.getHighlightFields().get("title").fragments();

                map.put("o_title", map.get("title"));

                String title = StringUtils.join(titles);
                if (StringUtils.isNotBlank(title)) {
                    map.put("title", title);
                }
                resultList.add(map);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //5 返回结果/ 图片封面
        ResponseResult result = ResponseResult.okResult(resultList);
        result.setHost(webSite);

        return result;
    }
}
